package com.education.common.handler;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.education.common.component.TenantProperties;
import com.education.common.context.TenantContext;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.expression.NullValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class CustomTenantHandler implements TenantLineHandler {

    private final TenantProperties tenantProperties;

    @Autowired
    public CustomTenantHandler(TenantProperties tenantProperties) {
        this.tenantProperties = tenantProperties;
    }

    /**
     * 超管标识
     */
    private static final String SUPER_ADMIN = "SuperAdmin";

    @Override
    public Expression getTenantId() {
        String tenantId = TenantContext.getCurrentTenant();

        if (tenantId == null) {
            return null; // 租户ID为空时不隔离
        }

        if (SUPER_ADMIN.equals(tenantId)) {
            return null; // 超管不隔离
        }

        if (tenantId.trim().isEmpty()) {
            return null; // 租户ID为空白时不隔离
        }

        try {
            return new LongValue(tenantId);
        } catch (NumberFormatException e) {
            return new StringValue(tenantId);
        }
    }


    /**
     * 获取租户字段名
     */
    @Override
    public String getTenantIdColumn() {
        return tenantProperties.getColumn();
    }

    /**
     * 根据表名判断是否忽略拼接多租户条件
     */
    @Override
    public boolean ignoreTable(String tableName) {
        // 判断当前用户是否为超管
        String tenantId = TenantContext.getCurrentTenant();
        // 如果插件未启用，则所有表都忽略
        if (!tenantProperties.isEnabled()) {
            return true;
        }
        // 超管不隔离
        if (SUPER_ADMIN.equals(tenantId)) {
            return true;
        }
        // 在忽略表中的表不处理
        return tenantProperties.getIgnoreTables().stream()
                .anyMatch(t -> t.equalsIgnoreCase(tableName));
    }
}